<template>
  <el-dialog
    :title="categories.id?'编辑分类':'新增分类'"
    :visible="isShowDislog"
    :close-on-click-modal="false"
    @close="isCancel"
  >
    <el-form ref="form" :model="categories" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="categories.title" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="categories.desc" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item label="封面">
        <ImagesUpload ref="ImagesUpload" />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button type="danger" size="small" @click="isCancel">取消</el-button>
      <el-button type="primary" size="small" @click="isOK">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import ImagesUpload from '@/components/ImagesUpload'
import { getCategoryApi, editCategoriesApi, addCategoriesApi } from '@/api/category'
export default {
  components: {
    ImagesUpload
  },
  props: {
    isShowDislog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      categories: {},
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 确定
    async isOK() {
      await this.$refs.form.validate()
      // console.log(this.$refs.ImagesUpload.fileList)
      const fileList = this.$refs.ImagesUpload.fileList
      const url = fileList[0] ? fileList[0].url : ''
      if (!url) {
        this.$message.warning('请上传封面')
        return
      }
      this.categories.image = url
      if (this.categories.id) {
        // 编辑
        await editCategoriesApi(this.categories)
        this.$message.success('编辑成功')
      } else {
        // 新增
        await addCategoriesApi(this.categories)
        this.$message.success('新增成功')
      }
      this.$parent.queryCategories()
      this.$parent.getCategoriesCoun()

      this.$emit('update:isShowDislog', false)
    },
    // 数据回显
    async getCategory(id) {
      const res = await getCategoryApi(id)
      // console.log(res)
      this.categories = res
    },
    getImage() {
      this.$refs.ImagesUpload.fileList.push({ url: this.categories.image })
    },

    // 取消
    isCancel() {
      this.$refs.form.resetFields()
      this.$refs.ImagesUpload.fileList = []
      this.categories = {}
      this.$emit('update:isShowDislog', false)
    },

    // 移除图片触发
    handleRemove() {}
  }
}

</script>

<style>

</style>
